import 'package:flutter_svg/flutter_svg.dart';
import 'package:pacsun/utils/PreferenceUtils.dart';
import 'package:pacsun/view/create/become/index.dart';
import 'package:pacsun/view/create/welcome_page.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:showcaseview/showcaseview.dart';

// Views
import 'package:pacsun/view/home/homeMain.dart' show HomeMain;
import 'package:pacsun/view/user/userMain.dart' show UserMain;
import 'package:pacsun/view/create/createCreatorMain.dart' show CreateCreatorMain;
import 'package:pacsun/view/explore/exploreMain.dart' show ExploreMain;
import 'package:pacsun/view/create/createNewerMain.dart' show CreateNewerMain;

// Providers
import 'package:pacsun/provider/themeProv.dart' show ThemeModeProvider;
import 'package:pacsun/provider/userProv.dart' show UserProvider;
import 'provider/tagProvider.dart';
import 'provider/productProvider.dart';
import 'provider/contentProvider.dart';
import 'package:pacsun/provider/taskDetailProv.dart';
import 'package:pacsun/provider/taskListProv.dart';
import 'package:pacsun/provider/termsProv.dart';
import 'package:pacsun/provider/sysTagsProvider.dart' show SysTagsProvider;
import 'package:pacsun/provider/putStoreProv.dart' show PutStoreProv;

// Utils
import 'package:pacsun/utils/theme.dart' show lightModeData, darkModeData;
import 'package:pacsun/utils/notifyMsg.dart' show notifyMsg;

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await PreferenceUtils.init();
  await dotenv.load(fileName: ".env");
  runApp(MyApp());
}

// Initialize deep linking

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    try {
      ScreenUtil().screenWidth;
    } catch (e) {
      ScreenUtil.init(
        context,
        designSize: const Size(375, 812),
        minTextAdapt: true,
        splitScreenMode: true,
      );
    }

    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (context) => ThemeModeProvider()),
        ChangeNotifierProvider(create: (context) => TagProvider()),
        ChangeNotifierProvider(create: (context) => UserProvider()),
        ChangeNotifierProvider(create: (context) => ProductProvider()),
        ChangeNotifierProvider(create: (context) => ContentProvider()),
        ChangeNotifierProvider(create: (context) => TaskDetailProv()),
        ChangeNotifierProvider(create: (context) => TaskListProv()),
        ChangeNotifierProvider(create: (context) => TermsProvider()),
        ChangeNotifierProvider(create: (context) => SysTagsProvider()),
        ChangeNotifierProvider(create: (context) => PutStoreProv()),
      ],
      child: ShowCaseWidget(
        autoPlayDelay: Duration(seconds: 1),
        enableAutoScroll: true,
        builder: (context) => MaterialApp(
          debugShowCheckedModeBanner: false,
          theme: context.read<ThemeModeProvider>().themeMode == ThemeMode.light
              ? lightModeData
              : darkModeData,
          darkTheme: darkModeData,
          home: const MainScaffold(),
        ),
      ),
    );
  }
}

class MainScaffold extends StatefulWidget {
  final int? targetIndex;

  const MainScaffold({super.key, this.targetIndex});

  @override
  State<MainScaffold> createState() => __MainScaffoldState();
}

class __MainScaffoldState extends State<MainScaffold> {
  int _currentIndex = 0;
  bool _isLoggedIn = false;
  int? _userType;
  bool _hasJustLoggedIn = false;

  @override
  void initState() {
    super.initState();
    if (widget.targetIndex != null) {
      _currentIndex = widget.targetIndex!;
    }
    _checkAuthStatus();
  }

  void _checkAuthStatus() {
    final userProvider = Provider.of<UserProvider>(context, listen: false);
    final wasLoggedIn = _isLoggedIn;

    setState(() {
      _isLoggedIn = userProvider.isLogin == true;
      _userType = userProvider.currentUser?.userType;

      // 如果之前未登录，现在登录了，标记为刚刚登录并跳转到Create页面
      if (!wasLoggedIn && _isLoggedIn) {
        _hasJustLoggedIn = true;
        if (_userType == 1) {
          _currentIndex = 2; // 跳转到Create页面
        }
        print('=== 登录成功，跳转到Create页面 ===');
        print('_currentIndex: $_currentIndex');
        print('_isLoggedIn: $_isLoggedIn');
        print('_userType: $_userType');
      }
    });
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final userProvider = Provider.of<UserProvider>(context);

    // 检查登录状态是否发生变化
    final currentLoginStatus = userProvider.isLogin == true;
    final currentUserType = userProvider.currentUser?.userType;

    print('currentLoginStatus:  ${currentLoginStatus}');
    print('currentUserType:  ${currentUserType}');

    if (_isLoggedIn != currentLoginStatus || _userType != currentUserType) {
      print('=== 检测到登录状态变化 ===');
      print('之前登录状态: $_isLoggedIn, 当前登录状态: $currentLoginStatus');
      print('之前用户类型: $_userType, 当前用户类型: $currentUserType');
      _checkAuthStatus();
    }
  }

  void _handleNavigation(int index) {
    if (index == 2 || index == 3) {
      if (!_isLoggedIn) {
        notifyMsg('Please login first', context);
        return;
      }
      if (index == 2 && _userType == 0) {
        Navigator.of(context).push(
          MaterialPageRoute(builder: (context) => BeComePage()),
        );
        return;
      }
    }
    setState(() {
      _currentIndex = index;
      _hasJustLoggedIn = false; // 用户手动切换页面后，清除刚登录标记
    });
  }

  @override
  Widget build(BuildContext context) {
    final themeProvider = Provider.of<ThemeModeProvider>(context);
    final _isLightMode = themeProvider.themeMode == ThemeMode.light;
    final _showGuide = PreferenceUtils.getBool('guide_executed');

    return Consumer<UserProvider>(
      builder: (context, userProvider, child) {
        // 在这里检查登录状态变化
        final currentLoginStatus = userProvider.isLogin == true;
        final currentUserType = userProvider.currentUser?.userType;

        if (_isLoggedIn != currentLoginStatus) {
          WidgetsBinding.instance.addPostFrameCallback((_) {
            print('_isLoggedIn$_isLoggedIn----$currentLoginStatus');
            if (!_isLoggedIn && currentLoginStatus) {
              // 刚刚登录成功
              setState(() {
                _isLoggedIn = currentLoginStatus;
                _userType = currentUserType;
                _hasJustLoggedIn = true;
                if (_userType == 1) {
                  _currentIndex = 2; // 跳转到Create页面
                }

                // WidgetsBinding.instance.addPostFrameCallback((_) {
                //   ShowCaseWidget.of(context).startShowCase([
                //     _one,
                //     _two,
                //   ]);
                // });
              });
            } else {
              setState(() {
                _isLoggedIn = currentLoginStatus;
                _userType = currentUserType;
              });
            }
          });
        }

        final List<Widget> _pages = [
          const HomeMain(),
          const ExploreMain(),
          _isLoggedIn
              ? CreateCreatorMain(showGuide: (_hasJustLoggedIn && !_showGuide))
              : const HomeMain(),
          // _isLoggedIn
          //     ? (_userType == 1
          //         ? CreateCreatorMain(
          //             showGuide: (_hasJustLoggedIn && !_showGuide))
          //         : CreateNewerMain(showGuide: _hasJustLoggedIn))
          //     : const HomeMain(),
          _isLoggedIn ? const UserMain() : const HomeMain(),
        ];

        final destinations = <NavigationDestination>[
          NavigationDestination(
            selectedIcon: SvgPicture.asset(
              'assets/icons/ic_home_selected.svg',
              width: 28,
              height: 28,
            ),
            icon: SvgPicture.asset(
              'assets/icons/ic_home.svg',
              width: 28,
              height: 28,
            ),
            label: 'Home',
          ),
          NavigationDestination(
            selectedIcon: SvgPicture.asset(
              'assets/icons/ic_explore_selected.svg',
              width: 28,
              height: 28,
            ),
            icon: SvgPicture.asset(
              'assets/icons/ic_explore.svg',
              width: 28,
              height: 28,
            ),
            label: 'Explore',
          ),
          NavigationDestination(
            selectedIcon: SvgPicture.asset(
              'assets/icons/ic_create_selected.svg',
              width: 28,
              height: 28,
              // color: Colors.white,
            ),
            icon: SvgPicture.asset(
              'assets/icons/ic_create.svg',
              width: 28,
              height: 28,
            ),
            label: 'Create',
          ),
          NavigationDestination(
            selectedIcon: SvgPicture.asset(
              'assets/icons/ic_mine_selected.svg',
              width: 28,
              height: 28,
            ),
            icon: SvgPicture.asset(
              'assets/icons/ic_mine.svg',
              width: 28,
              height: 28,
            ),
            label: 'Me',
          ),
        ];

        return Scaffold(
          bottomNavigationBar: Container(
            decoration: BoxDecoration(
              boxShadow: _isLightMode
                  ? [
                      BoxShadow(
                        color: const Color(0xFF000000).withAlpha(10),
                        offset: const Offset(0, -1),
                        blurRadius: 4,
                        spreadRadius: 0,
                      )
                    ]
                  : null,
            ),
            child: ClipRRect(
              borderRadius: const BorderRadius.only(
                topLeft: Radius.circular(20),
                topRight: Radius.circular(20),
              ),
              child: NavigationBar(
                backgroundColor: Color.fromRGBO(0, 0, 0, 1),
                onDestinationSelected: _handleNavigation,
                selectedIndex: _currentIndex,
                labelBehavior: NavigationDestinationLabelBehavior.alwaysShow,
                destinations: destinations,
              ),
            ),
          ),
          body: IndexedStack(
            index: _currentIndex,
            children: _pages,
          ),
        );
      },
    );
  }
}
